package com.bdth.bdthiss.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bdth.bdthiss.entity.*;
import com.bdth.bdthiss.service.*;
import com.bdth.bdthiss.util.MD5Utils;
import com.bdth.bdthiss.vo.GoodsVo;
import com.bdth.bdthiss.vo.MessageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2020/4/11.
 */
@RequestMapping("/goods")
@Controller
public class GoodsController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(GoodsController.class);
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ExcelgoodsService excelgoodsService;

    @Autowired
    private JdgoodsService jdgoodsService;
    @Autowired
    private CategoryExtendService categoryExtendService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodsPhotoRelationService goodsPhotoRelationService;

    @RequestMapping("saveGoods")
    @ResponseBody
    @Transactional
    public MessageResult saveGoods(GoodsVo goodsVo){
        //前期处理
        // 创建Goods
        Goods bean = new Goods();
        bean.setName(goodsVo.getGoodsname());
        bean.setGoodsNo(goodsVo.getGoodsno());
        bean.setModelId(0);
        bean.setSellPrice(new BigDecimal(goodsVo.getSellprice()));
        bean.setMarketPrice(new BigDecimal(goodsVo.getPrice()));
        //成本价
        bean.setCostPrice(new BigDecimal(0));
        bean.setUpTime(new Date());
        bean.setDownTime(new Date());
        bean.setCreateTime(new Date());
        //广告图片
        bean.setAdImg(null);
        bean.setImg(goodsVo.getGoodsimg());
        bean.setIsDel(goodsVo.getDownstate()==0?2:0);
        bean.setContent(goodsVo.getContext());
        bean.setKeywords("");
        //SEO描述
        bean.setDescription("");
        bean.setSearchWords("");
        bean.setWeight(new BigDecimal(0));
        bean.setUnit("件");
        bean.setBrandId(goodsVo.getBrandId());
        //查看次数
        bean.setVisit(MD5Utils.getRandomValue(1,100));
        bean.setFavorite(0);
        bean.setStoreNums(goodsVo.getGoodssum());
        bean.setSpecArray("");
        bean.setExp(0);
        bean.setComments(0);
        bean.setSale(0);
        bean.setGrade(0);
        bean.setSellerId(0);
        bean.setIsDeliveryFee(0);
        bean.setPromo("");
        bean.setActiveId(0);
        bean.setType("default");
        bean.setHash(0);
        try {
            goodsService.insert(bean);
        }catch (Exception e){
            logger.error("【"+bean.toString()+"】产品添加失败");
            return MessageResult.getSuccess("产品添加失败"+e.getMessage());
        }
        System.out.println(bean.getId());
        //添加图片 和 添加产品图片关联
        String goodspics = goodsVo.getGoodspics();
        String[] pics = goodspics.split("\r\n");
        for(int i=0;i<pics.length;i++){
            String pic = pics[i];
            if(pic!=null && pic.length()>0){
                String[] gps = pic.split(",");
                //组装图片对象
                GoodsPhoto temp = new GoodsPhoto();
                temp.setId(gps[0]);
                temp.setImg(gps[1]);
                //添加图片
                EntityWrapper<GoodsPhoto> entityWrapper1 = new EntityWrapper<>();
                entityWrapper1.eq("id",gps[0]);
                List<GoodsPhoto> goodphoto1 = goodsPhotoService.selectList(entityWrapper1);
                if(goodphoto1!=null && goodphoto1.size()>0){
                    logger.error("【" + gps[0] + "】图片已存在，不需要添加");
                }else {
                    try {
                        goodsPhotoService.insert(temp);
                    } catch (Exception e) {
                        logger.error("【" + gps[0] + "】图片已存在，不需要添加");
                    }
                }

                //组装产品图像关联对象
                GoodsPhotoRelation gpr = new GoodsPhotoRelation();
                gpr.setGoodsId(bean.getId());
                gpr.setPhotoId(gps[0]);
                //添加产品图集关联
                try {
                    goodsPhotoRelationService.insert(gpr);
                }catch (Exception e){
                    logger.error("【"+gps[0]+"】图片关联添加失败");
                }
            }
        }
        //添加产品类型关联
        //搜索顶级类型
        int typeid = goodsVo.getTypeid();
        Category typeCategory = categoryService.selectById(typeid);
        int topid = typeCategory.getParentId();
        CategoryExtend top = new CategoryExtend();
        top.setGoodsId(bean.getId());
        top.setCategoryId(topid);
        try {
            categoryExtendService.insert(top);
        }catch (Exception e){
            logger.error("【"+top.toString()+"】顶级产品类型添加失败");
        }

        //添加Type
        CategoryExtend type = new CategoryExtend();
        type.setGoodsId(bean.getId());
        type.setCategoryId(typeid);
        try {
            categoryExtendService.insert(type);
        }catch (Exception e){
            logger.error("【"+type.toString()+"】产品类型添加失败");
        }

        //添加子类型
        CategoryExtend sub = new CategoryExtend();
        sub.setGoodsId(bean.getId());
        sub.setCategoryId(goodsVo.getSubtypeid());
        try {
            categoryExtendService.insert(sub);
        }catch (Exception e){
            logger.error("【"+sub.toString()+"】产品子类型添加失败");
        }

        if(goodsVo.getType().equals("OFFICE")) {
            //修改excelgoods状态为已添加
            Excelgoods excelgoods = new Excelgoods();
            excelgoods.setId(goodsVo.getId());
            excelgoods.setDown(1);
            excelgoods.setStatus(1);
            excelgoods.setSuccess(1);
            //同时保持到excelgoods中
            excelgoods.setBrandid(goodsVo.getBrandId());
            excelgoods.setTypeid(goodsVo.getTypeid());
            excelgoods.setSubtypeid(goodsVo.getSubtypeid());
            excelgoods.setGoodssum(goodsVo.getGoodssum());
            excelgoods.setGoodsimg(goodsVo.getGoodsimg());
            excelgoods.setGoodsno(goodsVo.getGoodsno());
            excelgoods.setGoodspics(goodsVo.getGoodspics());
            try {
                excelgoodsService.updateById(excelgoods);
            } catch (Exception e) {
                return MessageResult.getSuccess("添加失败" + e.getMessage());
            }
        }

        if(goodsVo.getType().equals("JD")) {
            //修改excelgoods状态为已添加
            Jdgoods jdgoods = new Jdgoods();
            jdgoods.setId(goodsVo.getId());
            jdgoods.setDown(1);
            jdgoods.setStatus(1);
            jdgoods.setSuccess(1);
            //同时保持到excelgoods中
            jdgoods.setBrandid(goodsVo.getBrandId());
            jdgoods.setTypeid(goodsVo.getTypeid());
            jdgoods.setSubtypeid(goodsVo.getSubtypeid());
            jdgoods.setGoodssum(goodsVo.getGoodssum());
            jdgoods.setGoodsimg(goodsVo.getGoodsimg());
            jdgoods.setGoodsno(goodsVo.getGoodsno());
            jdgoods.setGoodspics(goodsVo.getGoodspics());
            try {
                jdgoodsService.updateById(jdgoods);
            } catch (Exception e) {
                return MessageResult.getSuccess("添加失败" + e.getMessage());
            }
        }
        return MessageResult.getSuccess("添加成功");
    }
}
